<template>
  <div class="input-tag-container">
    <el-autocomplete
        v-model="search"
        :fetch-suggestions="querySearch"
        placeholder="Enter a tag"
        @select="handleSelect"
        @keydown.enter="addTag"
        class="input"
    >
      <template #default="{ item }">
        <div class="suggestion-item">{{ item }}</div>
      </template>
    </el-autocomplete>
    <el-tag
        v-for="(tag, index) in tags"
        :key="index"
        closable
        @close="removeTag(index)"
        class="tag"
    >
      {{ tag }}
    </el-tag>
  </div>
</template>

<script setup>
import {ref, watch} from 'vue';
import {ElAutocomplete, ElTag} from 'element-plus';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(['update:modelValue']);

const tags = ref(props.modelValue);
const search = ref('');
const allTags = ['Vue', 'JavaScript', 'HTML', 'CSS', 'Node.js']; // 示例标签列表

const querySearch = (queryString, cb) => {
  const results = queryString
      ? allTags.filter(createFilter(queryString))
      : allTags;
  cb(results);
};

const createFilter = (queryString) => {
  return (tag) => {
    return tag.toLowerCase().includes(queryString.toLowerCase());
  };
};

const addTag = () => {
  if (search.value.trim() !== '' && !tags.value.includes(search.value.trim())) {
    tags.value.push(search.value.trim());
    search.value = '';
  }
};

const removeTag = (index) => {
  tags.value.splice(index, 1);
};

const handleSelect = (item) => {
  if (!tags.value.includes(item)) {
    tags.value.push(item);
    search.value = '';
  }
};

watch(tags, (newTags) => {
  emit('update:modelValue', newTags);
});
</script>

<style scoped>
.input-tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag {
  margin: 4px 0;
}

.input {
  flex: 1;
}

.suggestion-item {
  padding: 4px 8px;
  cursor: pointer;
}

.suggestion-item:hover {
  background-color: #f0f0f0;
}
</style>